#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>


int main()
{
    int pipefd[2] = {0};
    if(pipe(pipefd) != 0){
        perror("pipe fail");
        return 1;
    }

    // 0: 读取端, 1: 写入端
    printf("pipefd[0]: %d\n", pipefd[0]);
    printf("pipefd[1]: %d\n", pipefd[1]);
    
    // 父进程读取, 子进程写入
    if(fork() == 0){
        //子进程
        close(pipefd[0]);
        int count = 0;
        const char* msg = "Hello xwl!\n";
        while(1){
            write(pipefd[1], "a", 1);
            count++;
            printf("count: %d\n", count);
            //write(pipefd[1], msg, strlen(msg));
            //sleep(1);
        }

        exit(0);
    }

    //父进程
    close(pipefd[1]);
    while(1){
        sleep(10);
        //char c;
        //char c[64] = {0};
        char c[1024];
        ssize_t s = read(pipefd[0], c, 1023);
        c[s] = 0;
        printf("father taken: %s\n", c);
        /*
        sleep(1);
        char buff[64];
        若 read 返回0, 说明子进程关闭了文件描述符.
        ssize_t s = read(pipefd[0], buff, sizeof(buff) - 1);
        if(s == 0){
           printf("child quit\n");
           break;
        }
        else if(s > 0){
           buff[s] = 0;
           printf("child say to father: %s\n", buff);
        }
        else{
           printf("read error...\n");
           break;
        } 
        */
    }
    return 0;
}

